package com.biglead.mini.thread;


import com.biglead.mini.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Scope("prototype")//spring 多例
@Slf4j
@Component
public class BusinessThread implements Runnable{


    private String acceptStr;
    private Long  goodsId;


    private RedisTemplate redisTemplate;
    private RedisLockUtil redisLockUtil;


    public BusinessThread(String acceptStr, Long goodsId, RedisTemplate redisTemplate,RedisLockUtil redisLockUtil) {
        this.acceptStr = acceptStr;
        this.goodsId = goodsId;
        this.redisTemplate = redisTemplate;
        this.redisLockUtil = redisLockUtil;
    }

    public String getAcceptStr() {
        return acceptStr;
    }

    public void setAcceptStr(String acceptStr) {
        this.acceptStr = acceptStr;
    }



    @Override
    public void run() {
        String lockKey="lock:stock";
        String clientId = UUID.randomUUID().toString();
        long seconds =50l;

        try {
            //加锁
            boolean flag = redisLockUtil.tryLock(lockKey, clientId, seconds);
            //加锁成功
            if (flag) {
                log.info("加锁成功 clientId：{}", clientId);
                Integer stock = (Integer) redisTemplate.opsForValue().get("goodStock:" + goodsId);
                log.info("多线程当前库存：goodsId {} stock{}", goodsId, stock);
                if (stock <= 0) {
                    log.info("下单失败 库存不足：{}" + stock);
                    return;
                }
                //更新redis 缓存
                redisTemplate.opsForValue().decrement("goodStock:" + goodsId);
                log.info("多线程已经处理订单插入系统，订单号：" + acceptStr);
            }
        }catch (Exception e){

        }finally {
            redisLockUtil.unLock(lockKey, clientId);
        }
    }
}
